<template>
  <div ref="parentRef" class="watermark-container">
    <slot />
  </div>
</template>

<script>
import useWatermarkBg from './useWatermarkBg'
export default {
  name: 'Watermark',
  props: {
    fontSize: {
      type: Number,
      default: 40
    },
    gap: {
      type: Number,
      default: 20
    },
    text: {
      type: String,
      required: true,
      default: '禁止转载'
    }
  },
  mounted() {
    this.bg = useWatermarkBg(this.$props)
    this.resetWatermark()

    // 做一下用户删除拦截
    const observer = new MutationObserver(entries => {
      for (const entry of entries) {
        for (const node of entry.removedNodes) {
          if (node === this.div) {
            console.log('被删除了')
            this.resetWatermark()
          }
        }

        if (entry.target === this.div) {
          console.log('检测到样式修改')
          this.resetWatermark()
        }
      }
    })

    observer.observe(this.$refs.parentRef, { childList: true, attributes: true, subtree: true })

    this.$once('hook:beforeDestroy', () => {
      observer.disconnect()
    })
  },
  methods: {
    resetWatermark() {
      const { base64, size } = this.bg
      if (this.div) this.div.remove()

      const div = document.createElement('div')
      div.style.position = 'absolute'
      div.style.inset = '0'
      div.style.backgroundImage = `url(${base64})`
      div.style.backgroundRepeat = 'repeat'
      div.style.backgroundSize = `${size}px ${size}px`
      div.style.zIndex = 99999
      div.style.pointerEvents = 'none'
      this.$refs.parentRef.appendChild(div)

      this.div = div
    }
  }
}
</script>

<style lang="scss" scoped>
.watermark-container {
  position: relative;
  width: 100%;
}
</style>
